﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;
using App.Untiys;
using Newtonsoft.Json;
using System.Security.Permissions;

namespace App.Desk.Sdx
{
     
    public abstract class SdxApiWebClient
    {
        public class ResponseModel
        {
            public string Message { get; set; }
            public int Code { get; set; }

            public string Data { get; set; }

        }

       
        private static byte[] GuidParseHex(string Id)
        {
            byte[] array = new byte[Id.Length / 2];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = Convert.ToByte(Id.Substring(i * 2, 2), 16);
            }

            return array;
        }

        public static string GetProperties<T>(T t)
        {
            string text = string.Empty;
            if (t == null)
            {
                return text;
            }

            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            if (properties.Length <= 0)
            {
                return text;
            }

            PropertyInfo[] array = properties;
            foreach (PropertyInfo propertyInfo in array)
            {
                string name = propertyInfo.Name;
                object value = propertyInfo.GetValue(t, null);
                if (propertyInfo.PropertyType.IsValueType || propertyInfo.PropertyType.Name.StartsWith("String"))
                {
                    object[] customAttributes = propertyInfo.GetCustomAttributes(inherit: false);
                    string text2 = "";
                    if (customAttributes != null && customAttributes.Length > 0)
                    {
                        text2 = (customAttributes[0] as DisplayNameAttribute).DisplayName;
                    }

                    text += string.Format("{0}:{1}\r\n", name + "(" + text2 + ")", value);
                }
            }

            return text + "\r\n";
        }

        protected static ResponseModel PostData(string url, object data)
        {
            try
            {
                if (data is SdxBase @base)
                {
                    @base.FromIp = "";
                    @base.Token = "";
                    @base.FromIp = EnCodeString(GetIpListString());
                    @base.Token = EnCodeString(url + "/" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                }
                LogHelper.DoWriteLogTypeSubitem(LogType.Program, LogSubitem.DAS, $"Sdx>PostData jsonString:start");
                string jsonString = JsonConvert.SerializeObject(data);
                LogHelper.DoWriteLogTypeSubitem(LogType.Program, LogSubitem.DAS, $"Sdx>PostData jsonString:{jsonString}");
                if (string.IsNullOrEmpty(jsonString))
                    return new ResponseModel
                    {
                        Code = 1,
                        Message = "NoData",
                        Data = ""
                    };
                var result = SyncWrite(url, jsonString);
                if(!string.IsNullOrEmpty(result))
                {
                    return new ResponseModel
                    {
                        Code = 0,
                        Message = "Success",
                        Data = result
                    };
                }
                return new ResponseModel
                {
                    Code = 1,
                    Message = "NoData",
                    Data = ""
                };
            }
            catch (Exception ex)
            {
                LogHelper.DoWriteLogTypeSubitem(LogType.Program, LogSubitem.DAS, $"Sdx>PostData:{ex.StackTrace}");
                return new ResponseModel
                {
                    Code = 3,
                    Message = ex.Message,
                    Data = ""
                };
            }
        }

        protected static T Deserialize<T>(string jsonString)
        {
            return JsonConvert.DeserializeObject<T>(jsonString);
        }

        private static string SyncWrite(string url, string jsonString)
        {
            string text = string.Empty;
            try
            {
                WebClient webClient = new WebClient();
                Uri uri = new Uri(url);
                webClient.Headers[HttpRequestHeader.ContentType] = "application/json";
                webClient.Headers[HttpRequestHeader.Accept] = "application/json";
                byte[] bytes = Encoding.UTF8.GetBytes(jsonString);
                byte[] bytes2 = webClient.UploadData(url, "POST", bytes);
                text = Encoding.UTF8.GetString(bytes2);
                if (text == "null" || text == "[]")
                {
                }
                else
                {
                }
            }
            catch(Exception ex)
            {
                text = "";
                LogHelper.DoWriteLogTypeSubitem(LogType.Program, LogSubitem.DAS, $"Sdx>SyncWrite:{ex.StackTrace}");
            }
            return text;
        }

        private static string EnCodeString(string str)
        {
            byte[] array = Encoding.Unicode.GetBytes(str);
            List<byte> list = new List<byte>();
            if (str.Length <= 0)
            {
                return "";
            }

            string text = "sd@#%^$%^$%^,{}:?><";
            foreach (char c in text)
            {
                if (list.Count > 0)
                {
                    array = list.ToArray();
                    list.Clear();
                }

                for (int j = 0; j < array.Length; j++)
                {
                    byte b = array[j];
                    b = (byte)(b ^ c);
                    list.Add(b);
                }
            }

            return Encoding.Unicode.GetString(list.ToArray());
        }

        private static string GetIpListString()
        {
            string text = "";
            IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
            IPAddress[] array = addressList;
            foreach (IPAddress iPAddress in array)
            {
                if (iPAddress.AddressFamily == AddressFamily.InterNetwork)
                {
                    text = text + iPAddress.ToString() + ",";
                }
            }

            return text.TrimEnd(',');
        }
    }
}
